//基础比例相关
var fRoofRate = 0.27,
  fFuwaWidthDefaultRate = 0.3,
  fFuwaWidthRate = 0.3,
  fFuwaHeightRate = 0.25,
  //fFuwaBottomRate = 0.265,
  fFuwaBottomRate = 0.105,
  fJumpBaseRate = 0.1,
  fMoneySizeRate = 0.05,
  fMoneyBaseDur = 0.8,
  fMoneyBaseDelay = 0.5,
  fFingerHeightRate = 0.8,
  fBannerCellRate = 0.1;
var ENTRANCE_PATH = window.location.href;
var TOPDRAW_EPG_BASE_SERVER = "http://spring2020.topdraw.cn:8080/",
  TOPDRAW_EPG_SERVER = TOPDRAW_EPG_BASE_SERVER + "spring2020/";
var iWidth, iHeight; //屏幕宽高

//第一屏相关逻辑

//第二屏相关逻辑
var renderer,
  animation,
  move_stage = 1, //代表各个阶段，总共3阶段
  iFuwaLeft = null,
  iFuwaMoveRate = 0, //宝宝相对于屏幕宽度移动比率 初始为0
  iFuwaMoveRate2 = 0, //宝宝相对于背景移动比率 初始为0
  iFuwaMoveAll = 0, //宝宝相对于背景移动比率 初始为0
  iFuwaTop = null,
  iFuwaWidth = null,
  iFuwaHeight = null; //人物相关
var iRunStageLeft,
  iRunStageMoveRate = 0,
  iRunStageWidthRate = 0,
  iRunStageWidth = null;
var iMoneyCount = 30;
var iALive = iMoneyCount;
var aMoneyPath = ["img/bless2.png", "img/copper2.png", "img/ingots2.png"];
var iRoofHeight = null;
var aP = [1, 2, 3, 2, 1, 2, 1, 2, 1];
var oLiveInfo = {};
var oScoreInfo = {};
var iMoneySize = null;
var iTouchX = null;
var iTouchY = null;
var iTouchDisX = null;
var iTouchDisY = null;
var iMouseX = null;
var iMouseY = null;
var bStartMove = false;
var INITIAL_STATUS = 0;
var RUNNING_STATUS = 1;
var OVER_STATUS = 2;
var iStatus = INITIAL_STATUS;
var audioCollision = null;
var audioRun = null;
var iProducedCount = 0;
var bPageInited = false;
var DEFAULT_INTERVAL = 1000 / 60;
var strPageName = null;
var g_aPageThreePath = ["img/cai.jpg", "img/cai_sign.jpg","img/bg_intro.jpg"];
//html元素相关
var elHtml,
  $fuwa,
  $runstage,
  $moneylist,
  $roof,
  $scorelist,
  $bg,
  $bg_preload,
  $pageOne,
  $pageTwo,
  $bg_1,
  $bg_3,
  $aLi,
  $log,
  $bg_4;

//骨骼动画相关
var stage, skeltonResources;

var g_bMoveY = false;

var iBgH, iBgW;
$(document).ready(function() {
  // if (isWeiXin()) {
  //   initWXJDK();
  // }

  elHtml = $("html");
  iWidth = elHtml.width();
  iHeight = elHtml.height();

  initElements();
  showGauss();
});
function showGauss() {
  var iImgWidth, iImgHeight;
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  var img = new Image();
  img.src = "img/bg_1.jpg";
  var radius = 50;
  var leftMargin = 0,
    topMargin = 0;
  img.onload = function() {
    iImgWidth = (img.width / img.height) * iHeight;
    iImgHeight = iHeight;
    canvas.width = iImgWidth;
    canvas.height = iImgHeight;
    //初始化父容器的宽高使窗口与canvas宽高相同
    $("#content").css({
      width: iWidth + "px",
      height: iHeight + "px"
    });

    //左边距：(图片宽高 - canvas宽高) / 2;等于一边的边距宽高
    leftMargin = (iImgWidth - iWidth) / 2;
    topMargin = (iImgHeight - iHeight) / 2;

    //模糊图片的上边距与左边距
    $("#canvas").css("left", String(-leftMargin) + "px");
    initCanvas();
  };
  function initCanvas() {
    //创建圆
    region = {
      x: Math.random() * (iImgWidth - 2 * radius) + radius,
      y: Math.random() * (iImgHeight - 2 * radius) + radius,
      r: radius
    };
    draw(img, region);
  }
  function draw(img) {
    ctx.clearRect(0, 0, iImgWidth, iImgHeight);
    ctx.save();
    setRegion(region);
    /*绘制清楚图片，如leftMargin小于0那么取0，
  图片宽度与canvas宽度哪个最小取哪个值*/
    ctx.drawImage(img, leftMargin, topMargin, iImgWidth, iImgHeight);

    ctx.restore();
  }
  function setRegion(region) {
    ctx.beginPath();
    ctx.arc(region.x, region.y, region.r, 0, Math.PI * 2, false);
    //进行裁减圆
    ctx.clip();
  }
  window.reset = function(strPath) {
    $("#content").fadeIn(20);
    if (strPath) {
      img = new Image();
      img.src = strPath;
    }
    initCanvas();
  };
  window.show = function() {
    $("#content").fadeOut(2000);
    var animationBlur = setInterval(function() {
      region.r += 20;
      if (region.r > Math.max(iImgWidth, iImgHeight)) {
        clearInterval(animationBlur);
      }
      draw(img, region);
    }, 60);
  }
  initLoading(show);
}


function initLoading(cb) {
  var elTextLoading = $("#loading_progress");
  var aPreloadImg = [
    "img/bg_1.jpg",
    "img/bg_2.jpg",
    "img/bless.png",
    "img/bless2.png",
    "img/cai.jpg",
    "img/cai_sign.jpg",
    "img/circle.png",
    "img/copper.png",
    "img/copper2.png",
    "img/finger1.png",
    "img/finger2.png",
    "img/fu_sign.jpg",
    "img/fu.jpg",
    "img/ingots.png",
    "img/ingots2.png",
    "img/ji.jpg",
    "img/ji_sign.jpg",
    "img/kakemono.png",
    "img/move_bg.png",
    "img/text_1.png",
    "img/topdraw_logo.png"
  ];
  var len = aPreloadImg.length;
  var iRequestCount = len;
  for (var i = 0; i < len; i++) {
    var img = new Image();
    img.src = aPreloadImg[i];
    img.onload = img.onerror = function() {
      iRequestCount--;
      elTextLoading.html(Math.ceil(((len - iRequestCount) / len) * 100) + "%");
      if (!iRequestCount) {
        initPageOne();
        bPageInited = true;
        cb && cb();
      }
    };
  }
}
function initElements() {
  $pageOne = $("#page_one");
  $pageTwo = $("#page_two");
  $pageThree = $("#page_three");
  $pageFour = $("#page_four");
  $runstage = $("#run_stage");
  $moneylist = $("#money_list");
  $roof = $("#roof");
  $scorelist = $("#score_list");
  $bg_1 = $("#bg_1");
  $bg = $("#bg_2");
  $bg_3 = $("#bg_3");
  $bg_4 = $("#bg_4");
  $bg_preload = $("#bg_preload");
  $log = $("#log_div");
}

function initPageOne() {
  strPageName = "one";
  $pageOne.show();
  var iW = 480;
  var iH = 690;


  renderer = new PIXI.CanvasRenderer(iW, iH, {
    transparent: true
  });
  renderer.view.id = "zuoyi";
  $pageOne.append(renderer.view);
  stage = new PIXI.Container();
  PIXI.loader
    .add([
      { name: "spineCharacter", url: "data/zuoyi_1.json" },
      { name: "spineCharacter2", url: "data/pao.json" }
    ])
    .load(function(loader, resources) {
      skeltonResources = resources;
      animation = new PIXI.spine.Spine(resources.spineCharacter.spineData);
      stage.addChild(animation);
      animation.state.addAnimationByName(0, "Animation1", true, 0);
      animation.y = (2 / 3) * iH;
      animation.x = (1 / 2) * iW;
      animate1();
      $bg_1.removeClass("blur");
    });

  $("#touch_layer_one").click(function() {
    stage.removeChild(animation);
    cancelAnimationFrame(animate1);
    initPageTwo();
  });
  computeScene && computeScene();
}
function animate1() {
  requestAnimationFrame(animate1);
  if(strPageName == "one"){
    renderer.render(stage);
  }else{
    cancelAnimationFrame(animate1);
  }
}
function initPageThree() {
  strPageName = "three";
  computeScene && computeScene();
  setPageLayout(g_aPageThreePath, $bg_3);
  $pageThree.animate(
    {
      top: 0
    },
    500,
    function() {

      $pageTwo.animate({
        top: 10000 + "px"
      });
      show();
      window.setTimeout(function() {
        initPageFour();
      }, 3500);
    }
  );
  $pageThree.click(function() {
    initPageFour();
  });
}
function initPageFour() {
  strPageName = "four";
  swipePage();
  window.setTimeout(function() {
    initPageFive();
  }, 3500);
  $pageThree.click(function() {
    initPageFive();
  });
}
function initPageFive() {
  strPageName = "five";
  swipePage("rotate180",function(){
    $("#once_more").fadeIn(60);
    $("#once_more").click(function(){
      window.location.reload();
      // $pageOne.animate({
      //   top: -10000 + "px"
      // });
      // initPageOne();
    });
  });
  
}
function initPageTwo() {
  strPageName = "two";
  if (iHeight > iWidth) {
    reset("img/bg_2.jpg");
  }
  $pageOne.animate({
    top: -10000 + "px"
  });
  $pageTwo.fadeIn(300);
  $pageTwo.animate(
    {
      top: 0
    },
    300,
    function() {
      if (iHeight > iWidth) {
        show();
      }
    }
  );

  iFuwaWidth = 300;
  iFuwaHeight = 375;
  renderer.resize(iFuwaWidth, iFuwaHeight);
  renderer.view.id = "fuwa";

  $pageTwo.append(renderer.view);
  $fuwa = $("#fuwa");
  animation = new PIXI.spine.Spine(skeltonResources.spineCharacter2.spineData);
  stage.addChild(animation);
  animation.state.addAnimationByName(0, "Animation1", true, 0);

  animation.x = (1 / 2) * iFuwaWidth;
  animation.y = (iFuwaHeight * 46) / 55;
  iFuwaTop = $fuwa.offset().top;
  iFuwaWidth = $fuwa.width();
  iFuwaHeight = $fuwa.height();

  computeScene && computeScene();
  initMoney();

  if (iStatus == INITIAL_STATUS) {
    animate2();
  }

  ////注册鼠标事件
  document.addEventListener("mousedown", onMousedown, false);
  document.addEventListener("mouseup", onMouseup, false);
  //// 注册触摸事件
  document.addEventListener("touchstart", onTouchstart, false);
  document.addEventListener("touchmove", onTouchmove, false);
  document.addEventListener("touchend", onTouchend, false);

  //音频元素
  audioCollision = $("#collision_audio")[0];
  audioRun = $("#run_audio")[0];

  $("#money_audio")[0].play();
}
function animate2() {
  if (iStatus == OVER_STATUS) {
    cancelAnimationFrame(animate2);
    animation.state.setAnimationByName(0, "Animation2", true, 0);
    iFuwaMoveRate = 1 - fFuwaWidthRate;
    iFuwaMoveAll = iFuwaMoveRate + iFuwaMoveRate2;
    $fuwa.css({
      left: iFuwaMoveRate * 100 + "%",
      bottom : fFuwaBottomRate * 100 + "%"
    });
    checkMoney();

    //跳第三屏
    var aP = $("p", $scorelist);
    var iMax = 0;
    var iIndex = 0;
    for (var i = 0; i < aP.length; i++) {
      var iCount = parseInt(aP[i].innerText);
      if (iCount > iMax) {
        iIndex = i;
        iMax = iCount;
      }
    }
    var strPath3 = "";
    var strPath4 = "";
    switch (iIndex) {
      case 0:
        strPath3 = "img/fu.jpg";
        strPath4 = "img/fu_sign.jpg";
        break;
      case 1:
        strPath3 = "img/ji.jpg";
        strPath4 = "img/ji_sign.jpg";
        break;
      case 2:
        strPath3 = "img/cai.jpg";
        strPath4 = "img/cai_sign.jpg";
        break;
    }
    g_aPageThreePath = [strPath3, strPath4,"img/bg_intro.jpg"];
    window.setTimeout(function() {
      setPageLayout(g_aPageThreePath, $bg_3);
      initPageThree();
    }, 500);
  } else {
    requestAnimationFrame(animate2);
    moveScene();
  }
  if(bStartMove&&g_bMoveY){

  }else{
    renderer.render(stage);
  }
 
}
function moveScene(iX, iDur, fnCb, ib) {
  if(iX){
    iX = Math.min(iX,iHeight/1334*750/2);
    iX = iX/iHeight/1334*750*100;
    //console.log("iX",iX);
  }

  if(ib){
    g_bMoveY = true;
  }else{
    g_bMoveY = false;
  }
  iRunStageWidth = $runstage.width();
  iDur = iDur || 0;
  //iDis = iDis / iWidth;
  var iDis = fFuwaWidthRate*0.04*(iX ? iX+1 : 1);
  //console.log("iDis",(iX ? iX+1 : 1),fFuwaWidthRate*0.04,iDis);
  if (!isNaN(iFuwaLeft)) {
    //重复操作先矫正
    $fuwa.css({
      left: iFuwaMoveRate * 100 + "%"
    });
    if (iFuwaMoveRate < (1 - fFuwaWidthRate) / 2) {
      iFuwaMoveRate += iDis;
      iFuwaMoveRate = Math.min((1 - fFuwaWidthRate) / 2, iFuwaMoveRate);
      var o = {
        left: iFuwaMoveRate * 100 + "%"
      };
      if (ib) {
        o.bottom = ib * 100 + "%";
      }
      $fuwa.animate(o, iDur,"swing", function() {
        fnCb && fnCb();
      });
      move_stage = 1;
    }

    if (iFuwaMoveRate2 < iRunStageWidthRate - 1) {
      if (iFuwaMoveRate >= (1 - fFuwaWidthRate) / 2) {
        iFuwaMoveRate2 += iDis;
        iFuwaMoveRate2 = Math.min(iRunStageWidthRate - 1, iFuwaMoveRate2);
        var iCount = 3;
        var fnCheck = function() {
          iCount--;
          if (!iCount) {
            fnCb && fnCb();
          }
        };
        if (ib) {
          iCount += 1;
          $fuwa.animate(
            {
              left: iFuwaMoveRate * 100 + "%",
              bottom: ib * 100 + "%"
            },
            iDur,"swing",
            function() {
              fnCheck();
            }
          );
        }
        $runstage.animate(
          {
            left: -iFuwaMoveRate2 * 100 + "%"
          },
          iDur,
          function() {
            fnCheck();
          }
        );
        $moneylist.animate(
          {
            left: -iFuwaMoveRate2 * 100 + "%"
          },
          iDur,
          function() {
            fnCheck();
          }
        );
        $bg.animate(
            {
              left: -iFuwaMoveRate2 * 100 + "%"
            },
            iDur,
            function() {
              fnCheck();
            }
        );
      }
      move_stage = 2;
    }
    if (iFuwaMoveRate2 >= iRunStageWidthRate - 1) {
      if (iFuwaMoveRate <= 1 - fFuwaWidthRate) {
        iFuwaMoveRate += iDis;
        if (iFuwaMoveRate > 1 - fFuwaWidthRate) {
          iFuwaMoveRate = 1 - fFuwaWidthRate;
          iStatus = OVER_STATUS;
        }
        var o = {
          left: iFuwaMoveRate * 100 + "%"
        };
        if (ib) {
          o.bottom = ib * 100 + "%";
        }
        $fuwa.animate(o, iDur, "swing",function() {
          fnCb && fnCb();
        });
      } else {
        iStatus = OVER_STATUS;
      }
      move_stage = 3;
    }
    iFuwaMoveAll = iFuwaMoveRate + iFuwaMoveRate2;
    checkMoney();
    if (iStatus == INITIAL_STATUS) {
      iStatus = RUNNING_STATUS;
    }
  }
}
function computePosition() {
  if ($fuwa) {
    $fuwa.css({
      left: iFuwaMoveRate * 100 + "%"
    });
  }

  $runstage.css({
    left: -iFuwaMoveRate2 * 100 + "%"
  });

  $moneylist.css({
    left: -iFuwaMoveRate2 * 100 + "%"
  });
  $bg.css({
    left: -iFuwaMoveRate2 * 100 + "%"
  });
}
function computeScene() {
  //处理奔跑移动背景  宽度大于高度的情况下减一半
  if (iWidth > iHeight) {
    iRateElements = iHeight / 1334;
  } else {
    strFnClass = "remove";
  }
  var iTopOffset = 0;
  iBgH = iHeight;
  iBgW = (iHeight / 1334) * 750;
  if (iBgW > iWidth) {
    iBgW = iWidth;
    iBgH = (iBgW / 750) * 1334;
    iTopOffset = (iHeight - iBgH) / 2;
  }
  $(".finger_ani_wrapper").css({
    height: fFingerHeightRate * iBgW + "px"
  });
  if (strPageName == "one") {
    $pageOne.css({
      top: iTopOffset + "px",
      width: iBgW + "px",
      height: iBgH + "px"
    });
  }

  $bg_3.css({
    top: iTopOffset + "px",
    width: iBgW + "px",
    height: iBgH + "px"
  });
  $("#once_more").css({
    width : iBgW*364/750+"px",
    height : iBgW/750*108+"px",
    "margin-left" : -iBgW*364/750/2+"px"
  });
  fFuwaWidthRate = ((iHeight / 1334) * 750 * fFuwaWidthDefaultRate) / iWidth;
  if ($fuwa) {
    $fuwa.css({
      width: fFuwaWidthRate * 100 + "%"
    });
  }
  var elmoneys = $("#money_list img");
  if (elmoneys) {
    elmoneys.css({
      width: fMoneySizeRate * iHeight + "px",
      height: fMoneySizeRate * iHeight + "px"
    });
  }

  iRunStageWidthRate = ((($("#run_stage").height() / 727) * 3445) / iWidth) * 2;
  $runstage.css({
    width: iRunStageWidthRate * 100 + "%"
  });
  $bg.css({
    width: iRunStageWidthRate * 100 + "%"
  });
  iRunStageWidth = $runstage.width();
  $moneylist.width(iRunStageWidthRate * 100 + "%");
  iRoofHeight = $roof.height();
}
function initMoney() {
  var iH = fMoneySizeRate * iHeight;
  for (var i = 0; i < iMoneyCount; i++) {
    var iIndex ;//= aP[Math.floor(Math.random() * aP.length)] - 1;
    var fP = Math.random();
    if(fP < 0.5){
      iIndex = 1;
    }else if(fP < 0.8){
      iIndex = 2;
    }else{
      iIndex = 0;
    }
    var elImg = $(
      "<img src=" +
        aMoneyPath[iIndex] +
        ' style="width:' +
        iH +
        "px;height:" +
        iH +
        'px" />'
    );
    var elCell = $(
      "<div class='money_cell' style=\"opacity:0;left:-100px;\"></div>"
    );
    var elSubWrapper = $(
      "<div class='money_cell_sub' style=\"width:" +
        iH +
        "px;height:" +
        iH +
        'px" ></div>'
    );
    elCell.append(elSubWrapper);
    elSubWrapper.append(elImg);
    $moneylist.append(elCell);
    oLiveInfo[i] = {};
    oLiveInfo[i].alive = false;
    oLiveInfo[i].rotate = 0;
    oLiveInfo[i].type = iIndex;
    oScoreInfo[oLiveInfo[i].type] = 0;
    registerSpark(elCell, iIndex);
  }
  $moneylist.addClass("rotate_money");
}
function registerSpark(obj, index) {
  obj.click(function(e) {
    stopBubble(e);
    clickSpark.setParticleCount(30);
    clickSpark.setParticleSize(iFuwaWidth / 10);
    clickSpark.setParticleSpeed(18);
    clickSpark.setParticleImagePath(aMoneyPath[index]);
    clickSpark.fireParticles(obj);
  });
}
function stopBubble(e) {
  //如果提供了事件对象，则这是一个非IE浏览器
  if (e && e.stopPropagation) {
    //因此它支持W3C的stopPropagation()方法
    e.stopPropagation();
  } else {
    //否则，我们需要使用IE的方式来取消事件冒泡
    window.event.cancelBubble = true;
  }
}
function checkMoney(iDisX) {
  iDisX = iDisX || 0;
  var elImgs = $(".money_cell", $moneylist);
  var len = elImgs.length;
  var elImg;
  for (var i = 0; i < len; i++) {
    elImg = elImgs[i];
    elImg = $(elImg);
    iMoneySize = elImg.width();
    //检查碰撞
    var iLeft = elImg.offset().left;
    var iTop = elImg.offset().top;
    var iFuwaNowLeft = $fuwa.offset().left;
    var iFuwaNowTop = $fuwa.offset().top;
    var flag = false;

    if (
      ((iLeft > iFuwaNowLeft &&
        iLeft < iFuwaNowLeft + fFuwaWidthRate * iWidth) ||
        (iLeft < iFuwaNowLeft && iLeft + iMoneySize > iFuwaNowLeft - iDisX)) &&
      ((iTop > iFuwaNowTop && iTop < iFuwaNowTop + fFuwaHeightRate * iHeight) ||
        (iTop < iFuwaNowTop && iTop + elImg.height() > iFuwaNowTop))
    ) {
      elImg.trigger("click");
      audioCollision.currentTime = 0;
      audioCollision.play();
      oScoreInfo[oLiveInfo[i].type] += 1;
      oLiveInfo[i].alive = false;
      elImg.stop();
      elImg.animate(
        {
          opacity: 0
        },
        200
      );
      flag = true;
    }
    if (iLeft + iMoneySize < 0) {
      oLiveInfo[i].alive = false;
      elImg.stop();
      elImg.animate(
        {
          opacity: 0
        },
        200
      );
    }
    if (!oLiveInfo[i].alive) {
      var iMoneyLeftRate =
        100*(iFuwaMoveAll +
        fFuwaWidthRate +(
        ((Math.random()*3-1.5)+iProducedCount) * (1-fFuwaWidthRate-iFuwaMoveRate)/iMoneyCount ))/iRunStageWidthRate;

      var iMoneyBottomRate = Math.min(
        fFuwaBottomRate * 100 +
          Math.random() * fFuwaHeightRate * 100 * 3 +
          fMoneySizeRate * 100,
        90
      );
      elImg.stop();
      elImg.css({
        opacity: 1,
        left: iMoneyLeftRate + "%",
        bottom: iMoneyBottomRate + "%"
      });
      var elSub = $(".money_cell_sub", elImg);
      elSub.css({
        "animation-duration":
          Math.random() * fMoneyBaseDur + fMoneyBaseDur + "s",
        "animation-delay":
          Math.random() * fMoneyBaseDelay + fMoneyBaseDelay + "s"
      });
      elSub.children("img").css({
        "animation-duration":
          Math.random() * fMoneyBaseDur + fMoneyBaseDur + "s",
        "animation-delay":
          Math.random() * fMoneyBaseDelay + fMoneyBaseDelay + "s"
      });
      oLiveInfo[i].alive = true;
      iProducedCount++;
    }

    if (flag) {
      var elScoreCell = $(
        ".score_cell:eq(" + oLiveInfo[i].type + ")",
        $scorelist
      );
      var strHtml = elScoreCell.html();
      elScoreCell.html("");
      elScoreCell.html(strHtml);
      $("img", elScoreCell).addClass("active");
    }

    $("p:eq(" + oLiveInfo[i].type + ")", $scorelist).html(
      oScoreInfo[oLiveInfo[i].type]
    );
  }
}
function log(strInfo) {
  if ($log) {
    var str = $log.html();
    $log.html(str + strInfo + "<br/>");
  }
}
function onResizeCb() {
  if (!bPageInited) {
    return;
  }
  elHtml = $("html");
  if (elHtml.width() == iWidth && elHtml.height() == iHeight) {
    return;
  }
  var iBeforeMoveAll = iFuwaMoveAll;
  var iBeforeFuwaMoveRate = iFuwaMoveRate;
  var iBeforeFuwaWidthRate = fFuwaWidthRate;
  var iBeforeRunStageWidthRate = iRunStageWidthRate;

  iWidth = elHtml.width();
  iHeight = elHtml.height();

  computeScene && computeScene();

  var iRate2 =
    (iBeforeRunStageWidthRate + iBeforeFuwaWidthRate) /
    (iRunStageWidthRate + fFuwaWidthRate);
  var iRate3 =
    iBeforeFuwaMoveRate > 0 ? iBeforeFuwaMoveRate + iBeforeFuwaWidthRate : 0;

  iFuwaMoveRate = Math.max(iRate3 - fFuwaWidthRate, 0);
  iFuwaMoveAll = iBeforeMoveAll / iRate2;
  iFuwaMoveRate2 = iFuwaMoveAll - iFuwaMoveRate;
  iFuwaMoveRate2 = -Math.min(0,-iFuwaMoveRate2);
  computePosition();
  if (strPageName == "three" || strPageName == "four" || strPageName == "five") {
    setPageLayout(g_aPageThreePath, $bg_3);
    if (strPageName == "four") {
      $(".block_list").removeClass("rotate180");
      $(".block_list").addClass("rotate90");
    }
    if (strPageName == "five") {
      $(".block_list").removeClass("rotate90");
      $(".block_list").addClass("rotate180");
    }
  }
}
function onTouchstart(e) {
  //e.preventDefault();
  var touch = e.touches[0];
  if (iStatus == RUNNING_STATUS) {
    //e.offsetX和e.layerX都是手指在画布中的位置
    if (touch.pageX || touch.pageY) {
      if (bStartMove) {
        return;
      }
      bStartMove = true;
      iTouchX = parseInt(touch.pageX);
      iTouchY = parseInt(touch.pageY);
    }
  }
}
function onTouchmove(e) {
  var touch = e.touches[0];
  var iX = null;
  var iY = null;
  //e.offsetX和e.layerX都是手指在画布中的位置
  if (iStatus == RUNNING_STATUS) {
    if (!bStartMove) {
      return;
    }

    if (touch.pageX || touch.pageY) {
      if (iTouchX == null || iTouchY == null) {
        return;
      }
      iX = parseInt(touch.pageX);
      iY = parseInt(touch.pageY);
      iTouchDisX = iX - iTouchX;
      iTouchDisY = iY - iTouchY;
    }
  }
}
function onTouchend(e) {
  if (iStatus != RUNNING_STATUS) {
    return;
  }
  var fnCb = function() {
    bStartMove = false;
    iTouchX = null;
    iTouchY = null;
    iTouchDisX = null;
    iTouchDisY = null;
    //audioRun.currentTime = 0;
  };
  if (!iTouchDisX || iTouchDisX == 0) {
    iTouchDisY = iHeight - iTouchY - (fFuwaHeightRate + fRoofRate) * iHeight;
    var ib =
      (iHeight -
        (1 - fFuwaHeightRate - fRoofRate - fJumpBaseRate) * iHeight -
        fFuwaHeightRate * iHeight) /
      iHeight;
    if (
      iTouchDisY > 1 &&
      iTouchX >= iFuwaMoveRate * iWidth &&
      iTouchX < (iFuwaMoveRate + fFuwaWidthRate) * iWidth
    ) {
      ib = (iHeight - iTouchY - fFuwaHeightRate * iHeight) / iHeight;
    } else {
      //fnCb && fnCb();
      iTouchY = (1 - fFuwaHeightRate - fRoofRate - fJumpBaseRate) * iHeight;
    }
    $fuwa.stop();
    $fuwa.animate(
      {
        //bottom: ib * 100 + "%"
        bottom: (1 - fFuwaHeightRate) * 100 + "%"
      },
      300,"swing",
      function() {
        createBanner(
          iFuwaMoveRate * iWidth + (fFuwaWidthRate * iWidth) / 2,
          iTouchY
        );
        checkMoney(iTouchDisX);
        back2Roof(fnCb);
      }
    );
  } else {
    if (iTouchDisX && iTouchDisX > 0) {
      iTouchDisX = Math.min(iTouchDisX, iWidth / 2);
      //audioRun.currentTime = 0;
      audioRun.play();
      if (iTouchDisY && iTouchDisY < 0) {
        moveScene(
          iTouchDisX,
          300,
          function() {
            if (iStatus == RUNNING_STATUS) {
              $fuwa.stop();
              moveScene(
                iTouchDisX,
                300,
                function() {
                  if (
                    iStatus == RUNNING_STATUS &&
                    iRunStageWidthRate - iFuwaMoveRate2 > 1.5
                  ) {
                    //1.5是剩一半路程的时候不在加速往前走了 走else
                    $fuwa.stop();
                    moveScene(Math.max(80, iTouchDisX), 30, fnCb);
                  } else {
                    fnCb && fnCb();
                  }
                },
                fFuwaBottomRate
              );
            } else {
              back2Roof(fnCb);
            }
          },
          (fRoofRate * iHeight - iTouchDisY) / iHeight
        );
      } else {
        moveScene(iTouchDisX, 300, function() {
          moveScene(Math.max(80, iTouchDisX), 30, fnCb);
        });
      }
    }
  }
}
function back2Roof(fnCb, iTouchDisX) {
  $fuwa.animate(
    {
      bottom: fFuwaBottomRate*100 + "%"
    },
    300,
    function() {
      if (iTouchDisX) {
        moveScene(iTouchDisX / 2, 100, function() {
          fnCb && fnCb();
        });
      } else {
        fnCb && fnCb();
      }
    }
  );
}
function onMousedown(e) {
  if (iStatus == RUNNING_STATUS) {
    if (e.pageX) {
      if (bStartMove) {
        return;
      }
      bStartMove = true;
      iMouseX = parseInt(e.pageX);
      iMouseY = parseInt(e.pageY);
    }
  }
}
function onMouseup(e) {
  if (!bStartMove) {
    return;
  }
  var iDisX = 0;
  var iDisY = 0;
  var iX = null;
  var iY = null;
  if (iStatus == RUNNING_STATUS) {
    if (e.pageX) {
      if (iMouseX == null || iMouseY == null) {
        return;
      }
      iX = parseInt(e.pageX);
      iY = parseInt(e.pageY);
      iDisX = iX - iMouseX;
      iDisY = iY - iMouseY;
      var fnCb = function() {
        bStartMove = false;
        iMouseX = null;
        iMouseY = null;
        iDisX = null;
        iDisY = null;
        //audioRun.currentTime = 0;
      };
      if (!iDisX || iDisX == 0) {
        iDisY = iHeight - iY - (fFuwaHeightRate + fRoofRate) * iHeight;
        var ib =
          (iHeight -
            (1 - fFuwaHeightRate - fRoofRate - fJumpBaseRate) * iHeight -
            fFuwaHeightRate * iHeight) /
          iHeight;
        if (
          iDisY > 1 &&
          iX >= iFuwaMoveRate * iWidth &&
          iX < (iFuwaMoveRate + fFuwaWidthRate) * iWidth
        ) {
          ib = (iHeight - iY - fFuwaHeightRate * iHeight) / iHeight;
        } else {
          iTouchY = (1 - fFuwaHeightRate - fRoofRate - fJumpBaseRate) * iHeight;
        }
        $fuwa.stop();
        $fuwa.animate(
          {
            //bottom: ib * 100 + "%"
            bottom: (1 - fFuwaHeightRate) * 100 + "%"
          },
          300, "swing",
          function() {
            createBanner(
              iFuwaMoveRate * iWidth + (fFuwaWidthRate * iWidth) / 2,
              iY
            );
            checkMoney(iDisX);
            back2Roof(fnCb);
          }
        );
      } else {
        if (iDisX && iDisX > 0) {
          iDisX = Math.min(iDisX, iWidth / 2);
          //audioRun.currentTime = 0;
          audioRun.play();
          if (iDisY && iDisY < 0) {
            moveScene(
              iDisX,
              300,
              function() {
                if (iStatus == RUNNING_STATUS) {
                  $fuwa.stop();
                  moveScene(
                    iDisX,
                    300,
                    function() {
                      if (
                        iStatus == RUNNING_STATUS &&
                        iRunStageWidthRate - iFuwaMoveRate2 > 1.5
                      ) {
                        //1.5是剩一半路程的时候不在加速往前走了
                        $fuwa.stop();
                        moveScene(Math.max(80, iDisX), 30, fnCb);
                      } else {
                        fnCb && fnCb();
                      }
                    },
                    fFuwaBottomRate
                  );
                } else {
                  back2Roof(fnCb);
                }
              },
              (fRoofRate * iHeight - iDisY) / iHeight
            );
          } else {
            moveScene(iDisX, 300, function() {
              moveScene(Math.max(80, iDisX), 30, fnCb);
            });
          }
        }
      }
    }
  }
}
function calCos(x1, y1, x2, y2) {
  return (
    ((x1 - x2) / Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))) *
    (Math.abs(y2 - y1) / (y2 - y1))
  );
}
function isWeiXin() {
  //判断是否是微信浏览器的函数
  //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
  var ua = window.navigator.userAgent.toLowerCase();
  //通过正则表达式匹配ua中是否含有MicroMessenger字符串
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
}
function initWXJDK(fnCb) {
  var shareInfo = {
    link: ENTRANCE_PATH,
    title: "淘尽铅华，立于一画",
    description: "淘景立画祝您新春快乐",
    image: TOPDRAW_EPG_SERVER + "img/topdraw_logo.png"
  };
  $.getJSON(
    TOPDRAW_EPG_BASE_SERVER + "spring2020wechat/wx_config.html",
    { location: location.href },
    function(json) {
      //$.getJSON('http://localhost:8080/wechatlogin/wx_config.html', { 'location': location.href }, function (json) {
      if (json.businessCode == "success") {
        g_strUserId = json.t.replace(/\slogin/g, "");
        try {
          fnCb && fnCb();
        } catch (error) {}
        json.data.jsApiList = $.parseJSON(json.data.jsApiList);
        wx.config(json.data);
        wx.ready(function() {
          //需在用户可能点击分享按钮前就先调用
          // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）
          wx.updateAppMessageShareData({
            title: shareInfo.title, // 分享标题
            desc: shareInfo.description, // 分享描述
            link: shareInfo.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: shareInfo.image, // 分享图标
            success: function() {
              // 设置成功
            }
          });
          // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
          wx.updateTimelineShareData({
            title: shareInfo.title, // 分享标题
            link: shareInfo.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: shareInfo.image, // 分享图标
            success: function() {
              // 设置成功
            }
          });

          try {
            // 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
            wx.onMenuShareTimeline({
              title: shareInfo.title, // 分享标题
              link: shareInfo.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: shareInfo.image, // 分享图标
              success: function() {
                // 用户点击了分享后执行的回调函数
              }
            });
            // 获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
            wx.onMenuShareAppMessage({
              title: shareInfo.title, // 分享标题
              desc: shareInfo.description, // 分享描述
              link: shareInfo.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: shareInfo.image, // 分享图标
              type: "", // 分享类型,music、video或link，不填默认为link
              dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
              success: function() {
                // 用户点击了分享后执行的回调函数
              }
            });
            // 获取“分享到QQ”按钮点击状态及自定义分享内容接口（即将废弃）
            wx.onMenuShareQQ({
              title: shareInfo.title, // 分享标题
              desc: shareInfo.description, // 分享描述
              link: shareInfo.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: shareInfo.image, // 分享图标
              success: function() {
                // 用户确认分享后执行的回调函数
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
              }
            });

            // 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
            wx.onMenuShareWeibo({
              title: shareInfo.title, // 分享标题
              desc: shareInfo.description, // 分享描述
              link: shareInfo.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: shareInfo.image, // 分享图标
              success: function() {
                // 用户确认分享后执行的回调函数
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
              }
            });
            //  获取“分享到QQ空间”按钮点击状态及自定义分享内容接口（即将废弃）
            wx.onMenuShareQZone({
              title: shareInfo.title, // 分享标题
              desc: shareInfo.description, // 分享描述
              link: shareInfo.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: shareInfo.image, // 分享图标
              success: function() {
                // 用户确认分享后执行的回调函数
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
              }
            });
          } catch (e) {}
        });
      }
    }
  );
}
function createBanner(iX, iY) {
  var aBlessings = ["步步高升", "六六大顺", "财源滚滚", "年年有鱼"];
  var str = aBlessings[Math.floor(Math.random() * 4)];
  var arr = str.split("");
  arr.unshift("★");
  arr.push("★");
  var iH = (iHeight / 1334) * 750 * fBannerCellRate;
  var elDivSub = $(
    '<div style="top:' +
      iH +
      'px"><span style="width:' +
      iH +
      "px;height:" +
      iH +
      'px;background-position:0 0rem">' +
      arr[0] +
      "</span></div>"
  );
  var elTemp = elDivSub;
  for (var i = 1; i < arr.length; i++) {
    var el = $(
      '<div style="top:' +
        iH +
        'px"><span style="width:' +
        iH +
        "px;height:" +
        iH +
        "px;background-position:0 " +
        -i * iH +
        'px">' +
        arr[i] +
        "</span></div>"
    );
    elTemp.append(el);
    elTemp = el;
  }
  var elDiv = $(
    '<div class="wrap" style="position:absolute;width:' +
      iH +
      "px;height:" +
      iH +
      "px;left:" +
      (iX / iWidth) * 100 +
      "%;top:" +
      (iY / iHeight) * 100 +
      '%;"><h2>祝</h2></div>'
  );
  elDiv.append(elDivSub);
  $("body").append(elDiv);
  expandBanner(elDiv);
}
function collapseBanner(elDiv) {
  var aDiv = $("div", elDiv);
  var oTimer = null;
  var i = aDiv.length - 1;
  clearInterval(oTimer);
  oTimer = setInterval(function() {
    aDiv[i].className = "";
    i--;
    if (i < 0) {
      clearInterval(oTimer);
      elDiv.remove();
    }
  }, 50);
}
function expandBanner(elDiv) {
  var aDiv = $("div", elDiv);
  var oTimer = null;
  var i = 0;
  clearInterval(oTimer);
  if (aDiv.length) {
    oTimer = setInterval(function() {
      aDiv[i].className = "open";
      i++;
      if (i == aDiv.length) {
        clearInterval(oTimer);

        elDiv.animate(
          {
            top: (-elDiv.height() / iHeight) * 100 + "%"
          },
          3000,
          function() {
            elDiv.addClass("fadeInOut");
            collapseBanner(elDiv);
          }
        );
      }
    }, 100);
  }
}
function setPageLayout(aImgs, el) {
  el.html("");
  var iCountH = 4;
  var iCountV = 4;
  var iParentWidth = $("#bg_3").width();
  var iParentHeight = $("#bg_3").height();
  var iTotal = iCountH * iCountV;
  el.addClass("seg_bg");
  var str = "";
  var iWd = el.width();
  var iHt = el.height();
  var iW = iWd / 4;
  var iH = iHt / 4;

  for (var i = 0; i < iTotal; i++) {
    var str2 = "";
    for (var j = 0; j < aImgs.length; j++) {
      str2 =
        '<div style="width:' +
        iW +
        "px;height:" +
        iH +
        'px"><span style="background-size:' +
        iParentWidth +
        "px " +
        iParentHeight +
        'px"></span>' +
        str2 +
        "</div>";
    }

    str +=
      '<li><div class="block_list" style="transform-origin: center center -' +
      iW / 2 +
      'px;">' +
      str2 +
      "</div></li>";
  }
  el.html(str);
  $aLi = $("li", el);
  for (var i = 0; i < $aLi.length; i++) {
    var span = $aLi[i].getElementsByTagName("span");
    var str = "";
    for (var j = 0; j < span.length; j++) {
      span[j].style.backgroundImage = "url(" + aImgs[j] + ")";
      span[j].style.backgroundPosition =
        ((-i % iCountH) / 4) * iWd +
        "px " +
        (-Math.floor(i / iCountV) / 4) * iHt +
        "px";

      str +=
        ((-i % iCountH) / 4) * iWd +
        "px " +
        (-Math.floor(i / iCountV) / 4) * iHt +
        "px" +
        "====";
    }
  }
}
function swipePage(strClass,fnCb) {
  var i = 0;
  var timer = setInterval(function() {
    if (i == 3) {
      clearInterval(timer);
    }
    rotateBg(i, 1,strClass,fnCb);
    i++;
  }, 30);
}
function rotateBg(rows, dis,strClass,fnCb) {
  var timer2 = 0;
  var start = dis > 0 ? rows * 4 : (rows + 1) * 4 - 1;
  var end = dis > 0 ? (rows + 1) * 4 - 1 : rows * 4;
  timer2 = setInterval(function() {
    if (start == end) {
      clearInterval(timer2);
      fnCb&&fnCb();
    }

    var box = $(".block_list", $aLi[start]);
    box.addClass(strClass||"rotate90");
    start += dis;
  }, 60);
}
